import hashlib
import os

from baidubce import exception
from baidubce.services.bos.bos_client import BosClient

# 从配置文件中导入 BOS 相关配置
import bos_sample_conf


def get_md5(file_path):
    with open(file_path, 'rb') as f:
        md5 = hashlib.md5()
        while True:
            data = f.read(8192)
            if not data:
                break
            md5.update(data)
        return md5.hexdigest()


def upload_file_to_bos(local_file_path, bucket_name, object_key):
    bos_client = BosClient(bos_sample_conf.config)
    try:
        md5 = get_md5(local_file_path)
        response = bos_client.put_object_from_file(bucket_name, object_key, local_file_path)
        print(f"文件 {local_file_path} 已成功上传至 BOS 的 {bucket_name} 桶中，对象键为 {object_key}")
        print(f"返回的ETag: {response.etag}")
    except exception.BceServerError as e:
        print(f"上传文件至 BOS 时出现错误: {e}")
    except Exception as e:
        print(f"发生异常: {e}")


# 本地文件路径
local_file_path = r'Z:\xxxx\geek.zip'
# local_file_path = r"Z:\premium_v151/premium_v151_20230426.tar.gz"
bucket_name = "YOUR BucketName"  # BOS 桶名称
object_key = "xxx/xxxxx_20230426.tar.gz"  # 对象键
upload_file_to_bos(local_file_path, bucket_name, object_key)
